package com.example.app;

import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.app.ui.Discover.MentionActivity;
import com.example.app.ui.Discover.PrivacyActivity;
import java.util.ArrayList;
import java.util.List;
public class PostActivity extends AppCompatActivity {
    private static final int REQUEST_MEDIA = 101;
    private static final int MAX_IMAGES = 9;
    private EditText etContent;
    private RecyclerView rvMedia;
    private MediaAdapter mediaAdapter;
    private List<Uri> mediaUris = new ArrayList<>();
    private boolean isVideoSelected = false;
    private TextView tvPrivacy;
    private TextView tvMention;
    private TextView tvLocation;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);

        setupToolbar();
        setupContentEditor();
        setupMediaGrid();
        setupOptions();
    }
    private void setupToolbar() {
        findViewById(R.id.iv_back).setOnClickListener(v -> finish());
        TextView tvPost = findViewById(R.id.tv_post);
        tvPost.setOnClickListener(v -> postMoment());
        etContent = findViewById(R.id.et_content);
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                boolean hasContent = !TextUtils.isEmpty(s) || !mediaUris.isEmpty();
                tvPost.setEnabled(hasContent);
                tvPost.setTextColor(hasContent ?
                        ContextCompat.getColor(PostActivity.this, R.color.purple_700) :
                        ContextCompat.getColor(PostActivity.this, R.color.teal_200));
            }
        });
    }
    private void setupContentEditor() {
        etContent = findViewById(R.id.et_content);
        etContent.setHint("这一刻的想法...");
    }
    private void setupMediaGrid() {
        rvMedia = findViewById(R.id.rv_media);
        rvMedia.setLayoutManager(new GridLayoutManager(this, 3));
        mediaUris = new ArrayList<>();
        mediaUris.add(null);
        mediaAdapter = new MediaAdapter();
        rvMedia.setAdapter(mediaAdapter);
    }
    private void setupOptions() {
        View optionPrivacy = findViewById(R.id.option_privacy);
        tvPrivacy = optionPrivacy.findViewById(R.id.tv_value);
        View optionMention = findViewById(R.id.option_mention);
        tvMention = optionMention.findViewById(R.id.tv_value);
        View optionLocation = findViewById(R.id.option_location);
        tvLocation = optionLocation.findViewById(R.id.tv_value);
        optionPrivacy.setOnClickListener(v -> setPrivacy());
        optionMention.setOnClickListener(v -> mentionSomeone());
//        optionLocation.setOnClickListener(v -> setLocation());
    }
    private void postMoment() {
        finish();
    }
    public void selectMedia() {
        if (isVideoSelected) return;

//        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

        intent.setType("image/* video/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        startActivityForResult(intent, REQUEST_MEDIA);
    }

    private void addMedia(Uri uri) {
        String mimeType = getContentResolver().getType(uri);
        boolean isVideo = mimeType != null && mimeType.startsWith("video");

        // 视频处理
        if (isVideo) {
            isVideoSelected = true;
            mediaUris.clear();
            mediaUris.add(uri);
            return;
        }

        // 图片处理
        if (isVideoSelected) return; // 已选视频时忽略图片

        // 插入到最后一个位置前（保留添加按钮）
        int insertPosition = mediaUris.size() - 1;
        if (insertPosition < 0) insertPosition = 0;

        mediaUris.add(insertPosition, uri);
    }
    private class MediaAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private static final int TYPE_ADD = 0;
        private static final int TYPE_MEDIA = 1;
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_ADD) {
                View view = getLayoutInflater().inflate(R.layout.item_add_media, parent, false);
                return new AddViewHolder(view);
            } else {
                View view = getLayoutInflater().inflate(R.layout.item_media, parent, false);
                return new MediaViewHolder(view);
            }
        }
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof AddViewHolder) {
                holder.itemView.setOnClickListener(v -> selectMedia()); // 直接绑定点击事件

                holder.itemView.setVisibility(
                        mediaUris.size() >= MAX_IMAGES + 1 || isVideoSelected ? View.GONE : View.VISIBLE);
            } else {
                MediaViewHolder mediaHolder = (MediaViewHolder) holder;
                Uri uri = mediaUris.get(position);

                // 判断是否为视频（通过MIME类型）
                String mimeType = getContentResolver().getType(uri);
                boolean isVideo = mimeType != null && mimeType.startsWith("video");

                // 设置视频图标可见性
                mediaHolder.ivVideoIcon.setVisibility(isVideo ? View.VISIBLE : View.GONE);

                Glide.with(PostActivity.this)
                        .load(uri)
                        .into(mediaHolder.ivMedia);

                mediaHolder.ivDelete.setOnClickListener(v -> {
                    if (isVideo) {
                        isVideoSelected = false;
                    }
                    mediaUris.remove(position);
                    // 自动添加添加按钮
                    if (mediaUris.isEmpty() ||
                            (mediaUris.get(mediaUris.size()-1) != null && !isVideoSelected)) {
                        mediaUris.add(null);
                    }
                    notifyDataSetChanged();
                });
            }
        }
        @Override
        public int getItemCount() {
            return mediaUris.size();
        }

        @Override
        public int getItemViewType(int position) {
            return mediaUris.get(position) == null ? TYPE_ADD : TYPE_MEDIA;
        }
    }
    static class AddViewHolder extends RecyclerView.ViewHolder {
        AddViewHolder(View itemView) {
            super(itemView);
        }
    }
    private void setPrivacy() {
        Intent intent = new Intent(this, PrivacyActivity.class);
        startActivityForResult(intent, 102);
    }
    private void mentionSomeone() {
        Intent intent = new Intent(this, MentionActivity.class);
        startActivityForResult(intent, 103);
    }
    private void handleMediaSelection(Intent data) {
        if (data == null) return;
        ClipData clipData = data.getClipData();
        if (clipData != null) {
            for (int i = 0; i < clipData.getItemCount(); i++) {
                Uri uri = clipData.getItemAt(i).getUri();
                addMedia(uri);
            }
        }
        else if (data.getData() != null) {
            addMedia(data.getData());
        }
        updateMediaGrid();
    }
    private void updateMediaGrid() {
        if (!isVideoSelected && (mediaUris.isEmpty() || mediaUris.get(mediaUris.size()-1) != null)) {
            mediaUris.add(null);
        }
        if (mediaUris.size() > MAX_IMAGES + 1) {
            mediaUris = mediaUris.subList(0, MAX_IMAGES);
            mediaUris.add(null);
        }
        mediaAdapter.notifyDataSetChanged();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_MEDIA && resultCode == RESULT_OK) {
            handleMediaSelection(data); // 抽取媒体处理逻辑
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 102:
                    String privacy = data.getStringExtra("privacy");
                    tvPrivacy.setText(privacy);
                    break;
                case 103:
                    String mentions = data.getStringExtra("mentions");
                    tvMention.setText(mentions);
                    break;
                case 104:
                    String location = data.getStringExtra("location");
                    tvLocation.setText(location);
                    break;
            }
        }
    }
    static class MediaViewHolder extends RecyclerView.ViewHolder {
        ImageView ivMedia;
        ImageView ivVideoIcon;
        ImageView ivDelete;

        MediaViewHolder(View itemView) {
            super(itemView);
            ivMedia = itemView.findViewById(R.id.iv_media);
            ivVideoIcon = itemView.findViewById(R.id.iv_video_icon);
            ivDelete = itemView.findViewById(R.id.iv_delete);
        }
    }

}